package com.airycode.distribution.distribution1.page;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 * @date 2017/8/15
 */
public class DataPage<T extends Serializable> implements Serializable {

    private static final long serialVersionUID = -1371827642630435976L;

    /**
     * 页码
     */
    private int pageIndex = 1;

    /**
     * 每页记录数
     */
    private int pageSize = 20;

    /**
     * 总记录数
     */
    private int totalCount;

    /**
     * 分页记录
     */
    private List<T> list = new ArrayList<>();

    /**
     * 是否需要查询总记录数
     */
    private boolean needTotalCount = true;

    /**
     * 是否需要查询记录列表
     */
    private boolean needList = true;

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
        if (this.pageIndex <= 0) {
            this.pageIndex = 1;
        }
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
        if (this.pageSize <= 0) {
            this.pageSize = 20;
        }
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getList() {
        if (list == null) {
            return new ArrayList<>();
        }
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    @JsonIgnore
    public boolean isNeedTotalCount() {
        return needTotalCount;
    }

    public void setNeedTotalCount(boolean needTotalCount) {
        this.needTotalCount = needTotalCount;
    }

    @JsonIgnore
    public boolean isNeedList() {
        return needList;
    }

    public void setNeedList(boolean needList) {
        this.needList = needList;
    }

    public long getPageCount() {
        if (this.totalCount < 0L) {
            return -1L;
        }

        long count = this.totalCount / this.pageSize;
        if (this.totalCount % this.pageSize > 0L) {
            count += 1L;
        }
        return count;
    }

    @JsonIgnore
    public boolean hasNext() {
        return this.pageIndex + 1 <= getPageCount();
    }

    @JsonIgnore
    public int getNextPage() {
        if (hasNext()) {
            return this.pageIndex + 1;
        }
        return this.pageIndex;
    }

    @JsonIgnore
    public boolean hasPrev() {
        return this.pageIndex - 1 >= 1;
    }

    @JsonIgnore
    public int getPrevPage() {
        if (hasPrev()) {
            return this.pageIndex - 1;
        }
        return this.pageIndex;
    }

}
